/**
 * flow 流加载组件 
 * 改官方Flow.js
 * 反向
 */

layui.define('jquery', function (exports) {
  "use strict";

  var $ = layui.$, chatFlow = function (options) { }
    , ELEM_MORE = 'layui-flow-more'
    , ELEM_LOAD = '<i class="layui-anim layui-anim-rotate layui-anim-loop layui-icon ">&#xe63e;</i>';

  //主方法
  chatFlow.prototype.load = function (options) {
    var that = this, page = 0, lock, isOver, timer;
    options = options || {};

    var elem = $(options.elem); if (!elem[0]) return;
    var scrollElem = $(options.scrollElem || document); //滚动条所在元素
    var mt = options.mt || 50; //与临界距离
    var isAuto = 'isAuto' in options ? options.isAuto : true; //是否自动滚动加载
    var end = options.end || '没有更多了'; //“末页”显示文案

    //滚动条所在元素是否为document
    var notDocment = options.scrollElem && options.scrollElem !== document;

    //加载更多
    var ELEM_TEXT = '<cite>加载更多</cite>'
      , more = $('<div class="layui-flow-more"><a href="javascript:;">' + ELEM_TEXT + '</a></div>');

    if (!elem.find('.layui-flow-more')[0]) {
      elem.append(more);
    }

    var scrollToEnd = function () {//滚动到底部
      var h = $(document).height() - $(window).height();
      $(document).scrollTop(h);
    }

    //加载下一个元素
    var next = function (html, over) {
      html = $(html);
      more.after(html);//after/before
      over = over == 0 ? true : null;
      over ? more.html(end) : more.find('a').html(ELEM_TEXT);
      isOver = over;
      lock = null;
      if (page == 1) {
        scrollToEnd();
      }
    };

    //触发请求
    var done = function () {
      lock = true;
      more.find('a').html(ELEM_LOAD);
      typeof options.done === 'function' && options.done(++page, next);
    };

    done();

    //不自动滚动加载
    more.find('a').on('click', function () {
      var othis = $(this);
      if (isOver) return;
      lock || done();
    });

    if (!isAuto) return that;
    scrollElem.on('scroll', function () {
      var othis = $(this), top = othis.scrollTop();
      if (timer) clearTimeout(timer);
      if (isOver || !elem.width()) return; //如果已经结束，或者元素处于隐藏状态，则不执行滚动加载      
      timer = setTimeout(function () {
        //计算滚动所在容器的可视高度
        var height = notDocment ? othis.height() : $(window).height();
        //计算滚动所在容器的实际高度
        var scrollHeight = notDocment ? othis.prop('scrollHeight') : document.documentElement.scrollHeight;
        //向上临界点
        if ((top + height) >= (scrollHeight - mt)) {
          lock || done();
        }
      }, 100);
    });

    return that;
  };

  //暴露接口
  exports('chatflow', new chatFlow());
});
